<?php
namespace Home\Controller;
use Common\Controller\CommonController;

class OrderController extends CommonController {

	public function index(){
		$order=M('order');

		$status=I('status');
        $agent_city = I('agent_city');
        $agent_city = urldecode($agent_city);
		if($status!=''){
			$where = array('status'=>$status);
		}
		
		$keyword=I('key');
		if(!empty($keyword)){
			$where = array('code'=>$keyword);
		}
        if($agent_city){
            $agent_city = explode(' ', $agent_city);
            $pro = !empty($agent_city[0]) ? $agent_city[0] : '';
            $city = !empty($agent_city[1]) ? $agent_city[1] : '';
            $d = !empty($agent_city[2]) ? $agent_city[2] : '';
            if($pro && $city && $d){
                $where['c_addr'] = ['like', $pro.$city.$d.'%'];
            }else{
                $where['c_addr'] = 'nullnull';
            }
        }
		$Count=$order->where($where)->count();
		$Page = new \Think\Pager($Count,10);
		$show = $Page->showhtml();
		
		
		$orderList=$order->where($where)->limit($Page->firstRow.','.$Page->listRows)->order('id desc')->select();
		//echo M()->_sql();
		foreach ($orderList as $key => $value) {
			$uid=$value['uid'];
		
			$userInfo=M('user')->find($uid);
	
			$orderList[$key]['nickname']=$userInfo['nickname'];
			$orderList[$key]['phone']=$userInfo['phone'];

		}
		$this->assign('page',$show);
		$this->assign('list',$orderList);
		$this->display();
	}

	//取消订单
	public function Cancel(){
		$id = I('id');
		$res=M('Order')->where(array('id'=>$id))->save(array('status'=>5));
		if($res){
			$this -> redirect('Order/index');
		}
	}
	//取消订单
	public function ok(){
		$id = I('id');
		$res=M('Order')->where(array('id'=>$id))->save(array('status'=>3));
		if($res){
			$this -> redirect('Order/index');
		}
	}

	

	//添加物流信息
	public function logistics(){
		$id = I('id');
		$logistics_code=I("logistics_code");
		$logistics_type=I("logistics_type");

		$data = array(
			'id'=>$id,
			'logistics_code'=>$logistics_code,
			'logistics_type'=>$logistics_type,
			'wu_status'=>1,
			'read_status'=>0,
			'status'=>2,
            'delivery_time' => time(),
		);
	
		$logisticsInfo=M('order')->data($data)->save();

		if($logisticsInfo){
			$this->ajaxReturn(array('s'=>true,'m'=>'修改成功！'));
		}else{
			$this->ajaxReturn(array('s'=>false,'m'=>'修改失败！'));
		}
	}



	//订单详情
	public function orderInfo(){
			$code=I('code');
			$where = array("code"=>$code);
			$orderList=M('order_info')->where($where)->select();
			$order=M("order")->where("code=".$code)->find();
			foreach ($orderList as $key => $value) {
					$pid = $value['pid'];
					$aid = $value['aid'];
					$product_info=M("product")->where("id=".$pid)->find();
					$attr_info=M("product_attr")->where("id=".$aid)->find();
					$orderList[$key]['title'] = $product_info['title'];
					$orderList[$key]['price'] = $product_info['price']+$attr_info['dif'];
					$orderList[$key]['ds'] = $product_info['ds'];
					$orderList[$key]['attr'] = $attr_info['name'];	
			}
			if($orderList){
				$this->ajaxReturn(array('s'=>true,'d'=>$orderList,'o'=>$order));
			}else{
				$this->ajaxReturn(array('s'=>false));
			}
	}

	/**
	 * 确认付款
	 * @Author   张亚伟<1743325520@qq.com>
	 * @DateTime 2018-06-15
	 * @param    string                 $value [description]
	 * @return   [type]                        [description]
	 */
	public function confirm_pay()
	{
		$id = I('id');
		$info = M('order')->where(array('id' => $id))->find();
		if(empty($info)){
			$this->ajaxReturn(array('s'=>false,'m'=>'订单不存在'));
		}
		if($info['pay_status'] == 1 && $info['status'] == 1){
			$this->ajaxReturn(array('s'=>false,'m'=>'订单已付款'));
		}

		$res = M('order')->where(array('id' => $id))->save(array('pay_status' => 1, 'status' => 1));
		$re = M('order_info')->where(array('code' => $code))->select();
		foreach ($re as $key => $value) {
			$list=M('product')->where(array('id'=>$value['pid']))->find();
			$sales=$list['sales']+$value['num'];
			try {
				M('product')->where(array('id'=>$value['pid']))->data(array('sales'=>$sales))->save();
			} catch(Exception $e) {
				$this->ajaxReturn(array('s'=>false,'m'=>'修改失败！'));
			}
		}
		if ($res) {
			$this->ajaxReturn(array('s'=>true,'m'=>'修改成功！'));
		} else {
			$this->ajaxReturn(array('s'=>false,'m'=>'修改失败！'));
		}
	}

	/**
	 * 退款列表
	 * @return
	 */
	public function return_list()
	{
        $wd = I('wd');
        $map = [];
        if($wd){
            $map['order_no|refund_no'] = ['like', "%{$wd}%"];
        }
        list($list, $page) = $this->lists('Return', $map, 'id desc');
        if($list){
        	$return_types = C('ORDER_RETURN_TYPE');
        	$return_status = C('ORDER_RETURN_STATUS');
            if($user_ids = array_column($list, 'user_id')){
                $user_arr = D('user')->where(['id'=>['in', $user_ids]])->getField('id,nickname');
            }else{
                $user_arr = [];
            }
            foreach ($list as $key => &$row) {
            	$row['refund_type'] = isset($return_types[$row['refund_type']]) ? $return_types[$row['refund_type']] : '';
            	$row['status'] = isset($return_status[$row['status']]) ? $return_status[$row['status']] : '';
            	$row['create_time'] = date('Y-m-d H:i:s', $row['create_time']);
                if(isset($user_arr[$row['user_id']])){
                    // $row['is_feedback'] = 1;
                }else{
                    // $row['is_feedback'] = 0;
                }
            }
        }
        $this->assign('page',$page);
        $this->assign('list', $list);
        $this->display();
	}

	public function return_edit()
	{
		$id = I('id');
		$return = M('return')->where(['id'=>$id])->find();
		$return_goods = M('return_goods')->alias('rg')->join('__PRODUCT__ p ON rg.pid=p.id', 'LEFT')->join('__PRODUCT_ATTR__ pa ON rg.aid=pa.id', 'LEFT')->where(['rg.return_id'=>$id])->field('rg.*,p.title,listimg,p.price,pa.name as attr_name')->select();
		if(IS_POST){
			if(empty($return)){
				$this->error('退款单不存在');
			}
            $data = I('post.');
            if($return['status'] == 1){
            	if(!in_array($data['status'], [1, 2, 3])){
					$this->error('退款单未审核，请执行审核操作');
            	}
            }else if($return['status'] == 4){
            	if(!in_array($data['status'], [4, 5])){
					$this->error('请执行完成操作');
            	}
            }else{
				$this->error('操作失败，退款单状态不符合');
            }
            $returnModel = M('return');

            $refund_money_status = false;
            if($return['refund_type'] == 1){
            	// 售前退款
            	if($data['status'] == 2){
            		// 同意
            		$refund_money_status = true;
                    $data['status'] = 5;
            	}
            }else if($return['refund_type'] == 2){
            	// 售后退款
            	if($data['status'] == 5){
            		// 收货完成
            		$refund_money_status = true;
            	}
            }
            $res = M('return')->where(['id'=>$id])->save($data);
            if($res){
                if($refund_money_status){
                    $orderInfo = M('order')->where(['id'=>$return['order_id']])->find();
                    if($orderInfo){
                        M('order')->where(['id'=>$return['order_id']])->setInc('return_money', $return['money']);
                        $commission_logs = M('commission_log')->where(['from_type'=>'order', 'order_id'=>$return['order_id']])->select();
                        foreach ($commission_logs as $key => $commission) {
                            commission_log($commission['user_id'], 'return', $return['id'], $orderInfo['id'], '订单号：'.$orderInfo['code'], -$commission['money']);
                        }
                    }
                }
				$this->success('操作成功', U('return_list'));
            }else{
				$this->error('操作失败');
            }
		}else{
        	$return_types = C('ORDER_RETURN_TYPE');
        	$return_status = C('ORDER_RETURN_STATUS');
            $return['refund_type'] = isset($return_types[$return['refund_type']]) ? $return_types[$return['refund_type']] : '';
            $return['status_name'] = isset($return_status[$return['status']]) ? $return_status[$return['status']] : '';
            if($return_goods){
            	foreach ($return_goods as $key => &$goods) {
            		if($goods['listimg']){
            			$goods['listimg'] = json_decode($goods['listimg'], true);
            			if($goods['listimg']){
            				$goods['listimg'] = $goods['listimg'][0];
            			}
            		}
            	}
            }
	        $this->assign('info', $return);
	        $this->assign('return_goods', $return_goods);
	        $this->display();
		}
	}

	public function return_del()
	{
		
	}
}
